package com.coldworks.coldjoke.task;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.JokeDbManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.model.JokeModel;
import com.coldworks.coldjoke.ui.JokePageCell;
import com.coldworks.coldjoke.util.NetworkUtil;
import com.coldworks.coldjoke.util.UrlUtil;

public class VoteTask extends BaseThread {

	private Context context;
	private List<NameValuePair> params;
	private JokePageCell jokePageCell;
	private String jokesSort;
	private JokeModel jokeModel;
	private String itemType;
	private String msg = null;

	public VoteTask(Context context, JokePageCell jokePageCell,
			String pJokesSort, String itemType) {
		this.context = context;
		this.jokePageCell = jokePageCell;
		this.jokesSort = pJokesSort;
		this.jokeModel = jokePageCell.getJokeModel();
		this.itemType = itemType;
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("joke_id", jokeModel.getJokeId()));
		params.add(new BasicNameValuePair("item_type", itemType));
	}

	@Override
	public void run() {
		HttpPost httpPost = new HttpPost(UrlUtil.getCommentUrl());
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			httpPost.setHeader("Cookie", "webpy_session_id=" + sessionId);
			HttpResponse httpResponse = BaseNetworkManager.getInstance()
					.createHttpClient(context).execute(httpPost);
			if (isInterrupted()) {
				log.info("cancelled");
				return;
			}
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = httpResponse
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							httpResponse.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							httpResponse.getEntity().getContent());
				}
				if (jsonObject == null) {
					log.info("json result == null");
					return;
				}
				if (jsonObject.getString("success").equals("true")) {
					if (itemType.equals("like_joke")) {
						jokeModel.setLiked(1);
						jokeModel.setDisliked(0);
					} else {
						jokeModel.setLiked(0);
						jokeModel.setDisliked(1);
					}
					log.info("success");
					return;
				}
				//
				msg = jsonObject.getString("error_info");
				log.info(msg);
				if (itemType.equals("like_joke")) {
					jokeModel.setLiked(1);
					jokeModel.setDisliked(0);

				} else {
					jokeModel.setLiked(0);
					jokeModel.setDisliked(1);
				}
				return;

			} else {
				log.warn(String.valueOf(httpResponse.getStatusLine()
						.getStatusCode()));
				jokeModel.setLiked(-1);
				jokeModel.setDisliked(-1);
				return;
			}
		} catch (UnsupportedEncodingException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		} catch (JSONException e) {
			log.error("", e);
		} finally {
			JokeDbManager.getInstance().updateOneJoke(context, jokesSort,
					jokePageCell.getJokeModel());
			log.info(itemType + ":" + "done");
		}
	}
}